package com.qf.cx.simplenms.persist.service.impl;

import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.qf.cx.simplenms.persist.dao.api.ReaderDao;
import com.qf.cx.simplenms.persist.entity.AntennaEntity;
import com.qf.cx.simplenms.persist.entity.ReaderEntity;
import com.qf.cx.simplenms.persist.service.api.ReaderService;

@Service
@Transactional(value = "hibernateTransactionManager")
public class ReaderServiceImpl implements ReaderService {
	@Autowired
	private ReaderDao readerDao;

	@Override
	public void addReader(ReaderEntity reader) {
		readerDao.addReader(reader);
	}

	@Override
	public void deleteReader(String name) {
		readerDao.deleteReader(name);
	}

	@Override
	public void updateReader(ReaderEntity newReader) {
		ReaderEntity oldReader = readerDao.getReader(newReader.getName());
		oldReader.setDeviceSn(newReader.getDeviceSn());
		oldReader.setIp(newReader.getIp());
		oldReader.setLinkType(newReader.getLinkType());
		oldReader.setPort(newReader.getPort());
		List<AntennaEntity> olds = oldReader.getAntennaEntities();
		List<AntennaEntity> news = newReader.getAntennaEntities();

		for (Iterator<AntennaEntity> oldIt = olds.iterator(); oldIt.hasNext();) {
			AntennaEntity oldOne = oldIt.next();
			boolean find = false;
			for (Iterator<AntennaEntity> newIt = news.iterator(); newIt.hasNext();) {
				AntennaEntity newOne = newIt.next();
				if (oldOne.getId().equals(newOne.getId())) {
					oldOne.setAntenna(newOne.getAntenna());
					oldOne.setProtocol(newOne.getProtocol());
					newIt.remove();
					find = true;
					break;
				}
			}
			if (!find) {
				oldIt.remove();
			}
		}
		
		for (AntennaEntity each : news) {
			each.setReaderEntity(oldReader);
			olds.add(each);
		}

		readerDao.updateReader(oldReader);
	}

	@Override
	public ReaderEntity getReader(String name) {
		ReaderEntity reader = readerDao.getReader(name);
		return reader;
	}

	@Override
	public List<ReaderEntity> getReaders() {
		List<ReaderEntity> list = readerDao.getReaders();
		return list;
	}

	@Override
	public void addReaders(List<ReaderEntity> readers) {
		readers.forEach(t -> readerDao.addReader(t));
	}

}
